const os = require("os");
const { mineBlock, canMineBlock, fetchMyBlockData, postMyBlock } = require("../dist/cjs/circle-miner.js");
const { setNodeEnv } = require("../dist/cjs/circle-common.js");

async function main() {
  setNodeEnv("development");
  if (!canMineBlock()) {
    return;
  }

  const address = '15ea379mhPvKG95T3MnoCy9xuvTpusnXYx';
  const response = await fetchMyBlockData(address);
  console.log("fetchMyBlockData response:", JSON.stringify(response));
  const { status, data } = response;
  if (status === 200 && data) {
    const { blockHeaderHexString, channelId } = data;
    const cpus = os.cpus();
    console.log("find the cpu cores:", cpus.length);
    const result = await mineBlock(blockHeaderHexString, cpus.length - 1);
    console.log("mineBlock result:", JSON.stringify(result));
    if (result) {
      const items = result.split("\n");
      console.log(result);
      const minedBlockHeader = items[0];
      const postResult = await postMyBlock({
        address,
        channelId,
        blockHeaderHexString: minedBlockHeader
      });
      console.log("post mined block result:", JSON.stringify(postResult));
    }
  }
}

main().catch(err => console.error(err));
